


$(document).ready(function(){
    
    $('#ajaxButton').click(jsonFromAjax);
    
    jsonToTemplate();
    
});

function jsonToTemplate(){
    // parse the untrusted input from encoded text in the HTML template
    var data = JSON.parse(htmlDecode_jquery($('#init_data').text()));
    
    // this is a simple comment
     
    $('<div>', {
        text:'comment: '+data.comment
    }).appendTo('#content');
    // this is the attack, the decoded data must be shown as text but not HTML
    $('<div>', {
        text:'attack: '+data.attack
    }).appendTo('#content');  
    
    // XSS if render as HTML
    // $('<div>', {html:data.attack}).appendTo('#content');   
    
}

function jsonFromAjax(){
    
    // get the json from this url
    $.ajax('/ajax/json', 
    {
        type:'GET',
        data:{},
        dataType:'json'
    }).done(function(result) {            
        // success, parse the response
        var content = $('#dynamic_content');
        $("<div/>").text(result.comment).appendTo(content);
        $("<div/>").text(result.attack).appendTo(content);
        //XSS if render as HTML
        // $("<div/>").html(result.attack).appendTo(content);            
    })
    .fail(function() {
        console.log.error('Some errors');
    });        
}

// without jquery
function htmlDecode(input){
    var e = document.createElement('div');
    e.innerHTML = input;
    return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

// with jquery
function htmlDecode_jquery(value) {
    return (typeof value === 'undefined') ? '' : $('<div/>').html(value).text();
}
